package com.qf.service.impl;

import com.qf.TryException.AppException;
import com.qf.TryException.TryException;
import com.qf.anno.Retry;
import com.qf.entity.TbSeckillGoods;
import com.qf.entity.TbSeckillGoodsExample;
import com.qf.mapper.TbSeckillGoodsMapper;
import com.qf.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.core.Local;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author sky
 * @date 2022-08-19
 */
@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private TbSeckillGoodsMapper tbSeckillGoodsMapper;

    /**
     * 根据日期查询秒杀商品
     */
    @Override
    @Transactional(readOnly = true)
    public List<TbSeckillGoods> queryGoodsByTime(Date date) {
        TbSeckillGoodsExample example = new TbSeckillGoodsExample();
        example.createCriteria().andStartTimeLessThanOrEqualTo(date).andEndTimeGreaterThanOrEqualTo(date);
        List<TbSeckillGoods> tbSeckillGoods =  tbSeckillGoodsMapper.selectByExample(example);
        return tbSeckillGoods;
    }

    /**
     * 更新库存
     */
    @Override
    @Transactional
    @Retry
    public void updateNum(Long id){
        TbSeckillGoods tbSeckillGoods = tbSeckillGoodsMapper.selectByPrimaryKey(id);
        if (tbSeckillGoods==null){
            System.out.println("对不起，该商品不存在");
            throw new AppException("101","商品不存在");
        }
        if (tbSeckillGoods.getNum() <= 0){
            System.out.println("对不起，该商品库存不足");
            throw new AppException("101","商品库存不足");
        }
        Long version = tbSeckillGoods.getVersion();
        int i = tbSeckillGoodsMapper.updateNum(id, version);
        System.out.println("==============================" + i);
        if (i==0){
            throw new TryException("进行重试");
        }
    }

    /**
     * 根据商品id查询商品
     */
    @Override
    @Transactional(readOnly = true)
    public TbSeckillGoods findGoodsByid(Long id) {
        return tbSeckillGoodsMapper.selectByPrimaryKey(id);
    }

}
